# -*- coding: UTF-8 -*-
'''
Created on 2014年6月2日

@author: areshero
'''

from home.models import Ontology,Tag,ImageTag,Recommendations,TagType
from home import annotate
from multi_thread_recommend import startGetAnnotationsFromRecommender,startGetAnnotationsFromRecommender1
import urllib2
import json
import ontologies
import traceback

axes = "Anatomy", "Disease & Symptoms","Genetics, Proteins & Processes", "Imaging","Medical Intervention", "Pharmaceutical Agent"
ontologies = "SNOMEDCT", "SNOMEDCT", "GO","NCIT", "SNOMEDCT", "RXNORM"
REST_URL = "http://data.bioontology.org"
API_KEY = "1b466c88-c956-4682-8319-5e01f905b4f4"
class recommend:
    def __init__(self):
        self.recommend_list = []
    #get recommend result from Recommendation table
    def getTagIdAndNameOfImageByRecommendations(self,imageId, username):
        resultList = list()
        recommendations = Recommendations.objects.filter(image_id=imageId).values_list("tag_id", flat=True)
        imageTags = ImageTag.objects.filter(image_id=imageId, tag_id__in=recommendations, author_id=username)
        if len(imageTags) == 0:
            print 111
            return resultList
        for imageTag in imageTags:
            if imageTag.isSelected != 1:
                tmp_dict = {
                            'tagID':imageTag.tag.id,
                            'tagName': imageTag.tag.name,
                            'isSelected': imageTag.isSelected,
                            'tagType': imageTag.tag.tag_type.tag_type,
                            'ontologyName': imageTag.tag.ontology.name,
                            'ontologyID': imageTag.tag.ontology.id
                }
                resultList.append(tmp_dict)
        return resultList
    
    def isImageRecommended(self,figureID,ontology_ids):
        o = Recommendations.objects.filter(image_id = figureID)
        if(len(o) > 0):
            return True
        return False

def temp_saveRecommendTagFromDatabaseToImageTag(figureID, annotations, username):
    for index in range(len(annotations)):
        try:
            currentAnnotatedClass = annotations[index]["annotatedClass"]
            currentOntology = Ontology.objects.get(virtual_id = currentAnnotatedClass["links"]["ontology"])
            currentTag = Tag.objects.get(fullId = currentAnnotatedClass["@id"],ontology_id = currentOntology.id)
            if currentTag.tag_type_id == 4:
                currentTag.tag_type_id = '2'
                currentTag.save()
            imageTag = ImageTag.objects.filter(image_id=figureID, tag_id=currentTag.id, author_id=username)
            if len(imageTag) == 0:
                ImageTag.objects.get_or_create(image_id=figureID,
                                            tag_id=currentTag.id,
                                            author_id=username,
                                            isSelected=0)
            Recommendations.objects.get_or_create(tag_id=currentTag.id, image_id=figureID)
        except:
            print "saveerror"
            traceback.print_exc()
            pass
    return True
traceback
def saveRecommendTagFromDatabaseToImageTag(figureID,annotations, username):
    for currentAnnotation in annotations:
        for currentAnnotatedClass in currentAnnotation["annotatedClasses"]:
            try:
                #print currentAnnotatedClass["@id"]
                currentOntology = Ontology.objects.get(virtual_id = currentAnnotatedClass["links"]["ontology"])
                currentTag = Tag.objects.get(fullId = currentAnnotatedClass["@id"],ontology_id = currentOntology.id)
                
                
                if currentTag.tag_type_id == 4:
                    currentTag.tag_type_id = '2'
                    currentTag.save()
                imageTag= ImageTag.objects.filter(image_id = figureID,tag_id=currentTag.id, author_id=username)
                if len(imageTag) == 0:
                    ImageTag.objects.get_or_create(image_id = figureID,
                                               tag_id = currentTag.id,
                                               author_id = username,
                                               isSelected = 0
                                               )
                Recommendations.objects.get_or_create(tag_id =currentTag.id,image_id = figureID )
            except:
                pass
    return True

#从Recommendation表中查询数据结果
def saveRecommendTagFromRecommendations(figureID, username):
    recommendations = Recommendations.objects.filter(image_id = figureID).values_list("tag_id")
    for currentTagID in recommendations:
        currentImageTag = ImageTag.objects.filter(image_id = figureID,tag_id = currentTagID[0], author_id = username)
        if len(currentImageTag) == 0:
            ImageTag.objects.get_or_create(image_id = figureID,
                                               tag_id = currentTagID[0],
                                               author_id = username,
                                               isSelected = 0
                                               )

def get_json(url):
    try:
        opener = urllib2.build_opener()
        opener.addheaders = [('Authorization', 'apikey token=' + API_KEY)]
        jsonResult = json.loads(opener.open(url).read())
        return jsonResult, True
    except:
        return {}, False

def getAnnotationsFromRecommendREST(figureLegend, figureID, ontology_ids):
    annotations, isSuccessful = get_json(
                        REST_URL + 
                        "/annotator?max_level=1&text=" + 
                        urllib2.quote(figureLegend) + 
                        "&ontologies=" + ontology_ids
                        )
    return annotations, isSuccessful
# recommend for image with figurelegend among ontologies
# 

def do_my_work_recommender(figureID, figurelegend, ontology_ids, username):
    recommendInstance = recommend()
    if not recommendInstance.isImageRecommended(figureID, ontology_ids):
        # get recommendations from internet
        recommend_result, isSuccessful = getAnnotationsFromRecommendREST(figurelegend,figureID, ontology_ids)
        if not isSuccessful:
            print 'http error'
            return recommend_result
        temp_saveRecommendTagFromDatabaseToImageTag(figureID,recommend_result, username)
    else:
        # get recommendations from database
        saveRecommendTagFromRecommendations(figureID, username)
    return recommendInstance.getTagIdAndNameOfImageByRecommendations(figureID, username)
#调用函数，figureID为当前的图片id，figurelengend为要查询的词，ontology_ids为要查询的范围

